package com.nwpu.intimacy.login;

import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.nwpu.intimacy.R;
import com.nwpu.intimacy.main.MainActivity;
import com.nwpu.intimacy.utils.CacheUtil;

public class LoginActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/login";
	private static final String URL_F = "http://10.128.51.203:8080/SoftwareEngineer/contactlist";

	private LocationClient locationClient = null;
	private static final int UPDATE_TIME = 5000;
	private static int LOCATION_COUTNS = 0;

	private double Longitude = 0;
	private double Latitude = 0;

	private EditText username_edit;
	private EditText password_edit;
	private Button login_button;

	private CheckBox auto_login;

	private Button regist_btn;
	private Button getPassword_btn;

	private ProgressDialog progressDialog;

	private SharedPreferences sp_userMessage;

	private int exit_login;

	private String userNameValue;
	private String passwordValue;

	private Handler loginHandler;

	private final static int USER_LOGIN_SUCCESS = 0x114;
	private final static int USER_LOGIN_FAIL = 0x115;
	private final static int USER_INIT_SUCCESS = 0x116;

	private final int QR_WIDTH = 400;
	private final int QR_HEIGHT = 400;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		initActionBar();
		initLocation();

		locationClient.start();
		locationClient.requestLocation();

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		sp_userMessage
				.edit()
				.putBoolean("AUTO_ISCHECK",
						sp_userMessage.getBoolean("AUTO_ISCHECK", false))
				.commit();
		sp_userMessage
				.edit()
				.putBoolean("ISCHECK",
						sp_userMessage.getBoolean("ISCHECK", true)).commit();

		exit_login = getIntent().getIntExtra("exit_login", 1);

		initLayout();

		// 登陆
		login_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (isNetworkAvailable(getBaseContext())) {

				} else {

					Toast.makeText(getApplicationContext(),
							"No network connection, please try again!",
							Toast.LENGTH_SHORT).show();

				}

				String user_Name = username_edit.getText().toString();
				String password = password_edit.getText().toString();

				if (user_Name.equals("") || password.equals("")) {

					Toast.makeText(getApplicationContext(),
							"User name or password is blank, please re-enter!",
							Toast.LENGTH_SHORT).show();
					return;

				}

				// 先隐藏键盘
				((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(LoginActivity.this
								.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);

				progressDialog = new ProgressDialog(LoginActivity.this);
				progressDialog.setIcon(R.drawable.ic_launcher);
				progressDialog.setMessage("Loging....");
				progressDialog.show();

				new Thread(new Runnable() {

					@Override
					public void run() {
						try {

							Thread.sleep(1000);

							onChecked();

							/*
							 * Intent intent = new Intent();
							 * intent.setClass(getApplicationContext(),
							 * MainActivity.class); startActivity(intent);
							 */

						} catch (Exception e) {
							e.printStackTrace();
						} finally {

							progressDialog.dismiss();
						}
					}
				}).start();

			}

		});

		// 注册账号
		regist_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), RegisterActivity.class);
				startActivity(intent);

			}
		});

		// 忘记密码
		getPassword_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(),
						ForgotPasswordActivity.class);
				startActivity(intent);

			}
		});

		// 判断记住密码多选框的状态
		if (sp_userMessage.getBoolean("ISCHECK", false)) {
			// 默认是记录密码状态
			username_edit.setText(sp_userMessage.getString("USER_NAME", ""));
			password_edit.setText(sp_userMessage.getString("PASSWORD", ""));

			if (exit_login == 1) {
				// 判断自动登陆多选框状态
				if (sp_userMessage.getBoolean("AUTO_ISCHECK", false)) {
					// 设置默认是自动登录状态
					auto_login.setChecked(true);

					// 添加用户名和密码验证
					userNameValue = sp_userMessage.getString("USER_NAME", "");
					passwordValue = sp_userMessage.getString("PASSWORD", "");

					// 添加用户名和密码验证
					onChecked();

				}
			}
		}

		// 监听自动登录多选框按钮事件
		auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				if (auto_login.isChecked()) {

					System.out.println("自动登陆以选中");
					sp_userMessage.edit().putBoolean("AUTO_ISCHECK", true)
							.commit();

				} else {

					System.out.println("自动登录未选中");
					sp_userMessage.edit().putBoolean("AUTO_ISCHECK", false)
							.commit();

				}

			}
		});

		// 线程交互
		loginHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_LOGIN_SUCCESS: {
					// 跳转界面 登录成功

					try {

						// 获取用户信息生成二维码信息

						JSONArray jsonArray = new JSONArray(msg.obj.toString());
						JSONObject jsonObject = (JSONObject) jsonArray.get(0);
						JSONArray jsonArray2 = new JSONArray();
						JSONObject jsonObject2 = new JSONObject();

						jsonObject2.put("username",
								jsonObject.optString("username"));
						jsonObject2.put("area", jsonObject.optString("area"));
						jsonObject2.put("sex", jsonObject.optString("sex"));
						jsonObject2.put("comment",
								jsonObject.optString("comment"));

						jsonArray2.put(jsonObject2);

						Bitmap bitmap = stringtoBitmap(jsonObject
								.optString("portrait"));
						CacheUtil.WriteToFile(jsonObject.optString("username"),
								bitmap, "Photo");

						// 将用户信息存入本地数据库

						sp_userMessage.edit()
								.putString("USER_NAME", userNameValue).commit();

						sp_userMessage.edit()
								.putString("PASSWORD", passwordValue).commit();

						sp_userMessage
								.edit()
								.putString("AREA", jsonObject.optString("area"))
								.commit();
						sp_userMessage.edit()
								.putInt("SEX", jsonObject.optInt("sex"))
								.commit();
						sp_userMessage
								.edit()
								.putString("COMMENT",
										jsonObject.optString("comment"))
								.commit();

						createQRImage(jsonArray2.toString());

						initFriendsInformation();

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				case USER_INIT_SUCCESS: {

					Toast.makeText(getApplicationContext(),
							"Loging Successful", Toast.LENGTH_SHORT).show();

					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), MainActivity.class);
					startActivity(intent);
					break;

				}
				case USER_LOGIN_FAIL: {

					// 登陆失败，提示用户

					Toast.makeText(
							getApplicationContext(),
							"Account number or password is incorrect, please re-visit!",
							Toast.LENGTH_SHORT).show();

				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	public void initLocation() {

		locationClient = new LocationClient(this);

		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setCoorType("bd09ll");
		// option.setPriority(LocationClientOption.NetWorkFirst);
		option.setProdName("LocationDemo");
		option.setScanSpan(UPDATE_TIME);
		locationClient.setLocOption(option);

		locationClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {
				// TODO Auto-generated method stub
				if (location == null) {
					return;
				}

				Latitude = location.getLatitude();

				Longitude = location.getLongitude();

				Log.e("hkqhkqhkq", Latitude + " " + Longitude);

			}

			@SuppressWarnings("unused")
			public void onReceivePoi(BDLocation location) {
			}

		});

	}

	// 初始化所有控件
	public void initLayout() {

		username_edit = (EditText) findViewById(R.id.username_edit);
		password_edit = (EditText) findViewById(R.id.password_edit);
		login_button = (Button) findViewById(R.id.login_button);
		getPassword_btn = (Button) findViewById(R.id.getPassword_btn);

		auto_login = (CheckBox) findViewById(R.id.cb_auto);

		regist_btn = (Button) findViewById(R.id.regist_btn);

	}

	public void initActionBar() {

		getActionBar().setTitle("Intimacy");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().show();

	}

	// 验证用户登录
	public void onChecked() {

		new Thread() {

			public void run() {

				try {

					userNameValue = username_edit.getText().toString();
					passwordValue = password_edit.getText().toString();

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", userNameValue);
					jsonObject.put("password", passwordValue);
					jsonObject.put("longitute", Latitude);
					jsonObject.put("latitute", Longitude);
					jsonObject.put("currentip", getIPAdress());

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("login",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					/*
					 * String result = new String(
					 * EntityUtils.toString(httpResponse.getEntity()),
					 * HTTP.UTF_8);
					 */

					Log.e("hkq", URLDecoder.decode(result, HTTP.UTF_8));
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("status").equals("success")) {

						Message msg = new Message();
						msg.what = USER_LOGIN_SUCCESS;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_LOGIN_FAIL;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();
	}

	// 验证客户端是否联网
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {
			// cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// 生成二维码图片并保存于本地
	public void createQRImage(String url) {
		try {
			// 判断URL合法性
			if (url == null || "".equals(url) || url.length() < 1) {
				return;
			}

			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(url,
					BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
			int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
			// 下面这里按照二维码的算法，逐个生成二维码的图片，
			// 两个for循环是图片横列扫描的结果
			for (int y = 0; y < QR_HEIGHT; y++) {
				for (int x = 0; x < QR_WIDTH; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * QR_WIDTH + x] = 0xff000000;
					} else {
						pixels[y * QR_WIDTH + x] = 0xffffffff;
					}
				}
			}
			// 生成二维码图片的格式，使用ARGB_8888
			Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
			// 将生成的二维码存入本地
			CacheUtil.WriteToFile("QRCode", bitmap, "QRCode");

		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initFriendsInformation() {

		new Thread() {

			public void run() {

				try {

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", userNameValue);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL_F);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"friendsInformation", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					Log.e("hkq", URLDecoder.decode(result, HTTP.UTF_8));

					storageFriendInformation(result);

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}.start();

	}

	// 获取用户IP地址
	public String getIPAdress() {

		WifiManager wifiManager = (WifiManager) this
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int i = wifiInfo.getIpAddress();
		return int2ip(i);
	}

	public static String int2ip(int ipInt) {
		StringBuilder sb = new StringBuilder();
		sb.append(ipInt & 0xFF).append(".");
		sb.append((ipInt >> 8) & 0xFF).append(".");
		sb.append((ipInt >> 16) & 0xFF).append(".");
		sb.append((ipInt >> 24) & 0xFF);
		return sb.toString();
	}

	public void storageFriendInformation(String result) {

		try {

			JSONArray jsonArray = new JSONArray(result);
			JSONObject jsonObject = null;

			JSONArray storageArray = new JSONArray();

			for (int i = 0; i < jsonArray.length(); i++) {

				JSONObject storageObject = new JSONObject();

				jsonObject = (JSONObject) jsonArray.get(i);

				storageObject.put("username", jsonObject.optString("username"));
				storageObject.put("area", jsonObject.optString("area"));
				storageObject.put("signature",
						jsonObject.optString("signature"));
				storageObject.put("sex", jsonObject.optInt("sex"));

				storageArray.put(storageObject);

				Bitmap bitmap = stringtoBitmap(jsonObject.optString("portrait"));
				CacheUtil.WriteToFile(jsonObject.optString("username"), bitmap,
						"FriendPhoto");

			}

			CacheUtil.writeToFile(storageArray.toString(),
					"friendsInformation", "Friend");

			Message msg = new Message();
			msg.what = USER_INIT_SUCCESS;
			msg.obj = result;
			loginHandler.sendMessage(msg);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 将字符串转换成Bitmap图片
	 * 
	 * @param string
	 * @return
	 */
	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	protected void onDestroy() {
		super.onDestroy();
		if (locationClient != null && locationClient.isStarted()) {
			locationClient.stop();
			locationClient = null;
		}
	}

	/**
	 * 单击退出软件
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK: {

			Intent startMain = new Intent(Intent.ACTION_MAIN);
			startMain.addCategory(Intent.CATEGORY_HOME);
			startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(startMain);

			System.exit(0);
		}

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

}
